import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {UrlService} from '../common/service/url.service';
import {RelatedCondition} from '../model/related-condition';
import {Observable} from 'rxjs';
import {ApiRes} from '../common/model/response';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SubscriptionService {

  constructor(private http: HttpClient,
              private urlService: UrlService) {
  }

  // 获取政策领域分类  词表框架
  getFieldList(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/email/category');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      // res.result = this.transformTree(res.result);
      return res;
    }));

  }

  // 获取全部地域
  getAreas(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/email/regionV2');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      const selectList = [];

      // 数据预处理。 1.排序
      let arr = res.result;
      let orderArr = ['国家', '全国', '上海市'];      // 要排在最前面的区域。
      let newArr = [];
      for (var i = 0, len = orderArr.length; i < len; i++) {
        let word = orderArr[i];
        // if (arr.indexOf(word) !== -1) {
        if (arr[word]) {
          // newArr.push(word);
          // arr.splice(arr.indexOf(word), 1);
          newArr[word] = [];
          delete arr[word];

        }
      }
      // res.result = newArr.concat(arr);
      res.result = Object.assign(newArr, arr);

      // for (let i = 0; i < res.result.length; i++) {
      //   selectList.push({});
      //   selectList[i].label = res.result[i];
      //   selectList[i].value = res.result[i];
      // }
      // res.result = selectList;
      return res;
    }));

  }

  // 提交订阅
  submitForm(condition: any): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/email/add');
    return this.http.post<ApiRes>(url, condition);

  }

  // 取消订阅
  cancelSubmit(email: string): Observable<ApiRes> {
    const params = new HttpParams().append('email', email);
    const url = this.urlService.getWebUrl('/email/delete');
    return this.http.get<ApiRes>(url, {params});

  }

// 将后台数据格式化成级联选择器需要的数据格式
  transformTree(result: any) {
    const treeData = [];
    for (let i = 0; i < result.length; i++) {
      treeData.push({});
      treeData[i].label = result[i].name;
      treeData[i].value = result[i].id;
      treeData[i].isLeaf = !result[i].children.length;
      if (!result[i].children.length) {
        return treeData[i];
      }
      treeData[i].children = [];
      treeData[i].children.push(this.transformTree(result[i].children));
    }
    return treeData;


  }
}
